package com.atguigu.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ConstanPropertiseUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = ConstanPropertiseUtils.END_POIND;
// 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
        String accessKeyId = ConstanPropertiseUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstanPropertiseUtils.ACCESS_KEY_SECRET;
        String buckName = ConstanPropertiseUtils.BUCKET_NAME;

        try{
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            String originalFilename = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            originalFilename=uuid+originalFilename;

            //按日期进行分类
            String datePath = new DateTime().toString("yyyy-MM-dd");
            originalFilename = datePath+"/"+originalFilename;
            // 上传文件流。
            InputStream inputStream = file.getInputStream();
            ossClient.putObject(buckName,originalFilename , inputStream);
            ossClient.shutdown();
            String url ="https://"+buckName+"."+endpoint+"/"+originalFilename;
            //"https://myedu-2021.oss-cn-beijing.aliyuncs.com/"+file.getName();
            return url;
        }catch (Exception e){
            e.printStackTrace();
        }



// 关闭OSSClient。

        return null;
    }
}
